package com.xukehong.demo.util;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.*;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author: xkh
 * @Date: 2019/3/22 9:23
 * @Version 1.0
 */
public class FileUploadUtil {


    /**
     * @param file 文件
     */
    public static String uploadUtil(MultipartFile file, String filePath) throws Exception {
        File dir = new File(filePath);
        //安全检测文件是否是真图片
        if(!isImage(multipartFileToFile(file))){
            return "请上传正确的图片";
        }
        //文件夹不存在，则创建
        if (!dir.exists()) {
            dir.mkdir();
        }
        String suffixName = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
        //服务端保存的文件对象
        File serverFile = new File(dir + "/" +  UUID.randomUUID()+suffixName);
        //将上传的文件写入到服务端文件内
        try {
            file.transferTo(serverFile);
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
        Thumbnails.of(serverFile).outputQuality(0.5f).size(100,100).toFile(filePath+serverFile.getName());
        return "上传成功";
    }

    /**
     * 多个文件上传
     */
    public static String uploadsUtil(List<MultipartFile> files, String filePath) {
        File dir = new File(filePath);
        //文件夹不存在，则创建
        if (!dir.exists()) {
            dir.mkdir();
        }
        for (MultipartFile file : files) {
            String suffixName = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
            //服务端保存的文件对象
            File serverFile = new File(dir + "/" +  UUID.randomUUID()+suffixName);
            try {
                file.transferTo(serverFile);
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败";
            }
        }
        return "上传成功";
    }

    public static boolean isImage(File imageFile) {
        if (!imageFile.exists()) {
            return false;
        }
        Image img = null;
        try {
            img = ImageIO.read(imageFile);
            if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            img = null;
        }
    }

    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
